/*
 * @FileName: OrganizationService.java
 * 
 * @Author
 * 
 * @Description:
 * 
 * @Date 2016年1月7日 下午2:42:39
 * 
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import cn.hpclub.server.model.Organization;

/**
 * Class description goes here
 *
 * @author
 */
public class OrganizationService{
    private static final Logger       logger  = LoggerFactory.getLogger(OrganizationService.class);

    public static OrganizationService service = new OrganizationService();

    public String tree(int id){

        List<Record> pager_list = Organization.dao.tree(id);
        JSONObject temp = new JSONObject();
        JSONObject jo = new JSONObject();
        JSONArray ja = new JSONArray();
        JSONObject result = new JSONObject();
        HashMap<String, JSONObject> map = new HashMap<String, JSONObject>();
        for(int i = 0; i < pager_list.size(); i++){
            Record r = pager_list.get(i);
            if(r.getInt(Organization.ID) == id){
                result.put("title", r.get(Organization.DISPLAYNAME).toString());
                result.put("type", "folder");
                result.put("attr", new JSONObject().put(Organization.ID, r.get(Organization.ID).toString()));

            } else if(r.get(Organization.ORGSIGN).toString().equals("2")){
                jo = new JSONObject();
                jo.put("title", r.get(Organization.DISPLAYNAME).toString());
                jo.put("type", "folder");
                jo.put("attr", new JSONObject().put(Organization.ID, r.get(Organization.ID).toString()));
                jo.put("products", new JSONArray());
                map.put(r.get(Organization.ID).toString(), jo);
            }
        }

        for(int i = 0; i < pager_list.size(); i++){
            Record r = pager_list.get(i);
            try{
                if(map.containsKey(r.get(Organization.PARENTID).toString())){
                    temp = map.get(r.get(Organization.PARENTID).toString());
                    ja = temp.getJSONArray("products");
                    jo = new JSONObject();
                    jo.put("title", r.get(Organization.DISPLAYNAME).toString());
                    jo.put("type", "item");
                    jo.put("attr", new JSONObject().put(Organization.ID, r.get(Organization.ID).toString()));
                    ja.put(jo);
                    temp.put("products", ja);
                    map.put(r.get(Organization.PARENTID).toString(), temp);
                }
            }
            catch(Exception e){

                e.printStackTrace();
            }
        }
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        ja = new JSONArray();

        while(it.hasNext()){
            temp = map.get(it.next());
            ja.put(temp);

        }
        result.put("products", ja);

        return new JSONArray().put(result).toString();

    }

    public String load(UploadFile upfile){

        String result = "";

        File upload = null;
        if(upfile != null){
            upload = upfile.getFile();
        }
        if(upload == null){
            result = "请选择上传文件!";
            return result;
        }

        try{
            result = importData(new FileInputStream(upload));
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
            result = "导入文件解析出错!";
        }
        return result;
    }

    /**
     * @Title: importData
     * @Description:导入机构数据
     * @param inputStream
     *            源数据
     * @return String
     */
    public String importData(FileInputStream inputStream){
        String[] result;
        String mag = null;
        int count_class = 0;
        int count_1 = 0;
        int count_2 = 0;
        int count_3 = 0;

        int ori_count_1 = 0;
        int ori_count_2 = 0;
        int ori_count_3 = 0;

        int map_count_1 = 0;
        int map_count_2 = 0;
        int map_count_3 = 0;

        BufferedReader reader = null;
        InputStreamReader read = null;
        try{
            System.gc();
            read = new InputStreamReader(inputStream, "gbk");
            reader = new BufferedReader(read);
            String tempString = null;
            HashMap<String, JSONObject> map_level1 = new HashMap<String, JSONObject>(); // 一级机构：成都
            HashMap<String, JSONObject> map_level2 = new HashMap<String, JSONObject>(); // 二级机构：成都新都区
            HashMap<String, JSONObject> map_level3 = new HashMap<String, JSONObject>(); // 三级机构：新都店铺
            JSONObject temp = null;
            String[] value;
            String sql_class = "insert into organization_class (id,WebsiteId,class_name) value ";

            String sql_class_dup = " ON DUPLICATE KEY UPDATE enabled=1,class_name=values(class_name)";

            int i = 0;
            // 一次读入一行，直到读入null为文件结束
            while((tempString = reader.readLine()) != null){

                value = tempString.split("\\$");

                // 过滤非法数据
                if(!isValid(value)){
                    continue;
                }

                // 导入一级机构：成都
                // map_level1.put(value[2], value[3]);

                if(value[0].equals(value[2])){
                    ori_count_1++;
                    temp = new JSONObject();
                    temp.put(Organization.DISPLAYNAME, value[1]).put(Organization.WEBSITEID, value[8])
                            .put(Organization.SALESCENTERID, StrKit.isBlank(value[6]) ? '0' : value[6])
                            .put(Organization.SALESCENTERNAME, value[7])
                            .put(Organization.ENABLED, value[10].equals("0") ? "1" : "0");
                    map_level1.put(value[0], temp);
                }

                // 导入二级机构：新都区
                if(value[0].equals(value[4])){
                    ori_count_2++;
                temp = new JSONObject();
                    temp.put(Organization.DISPLAYNAME, value[1]).put(Organization.PARENTID, value[2])
                            .put(Organization.WEBSITEID, value[8])
                            .put(Organization.SALESCENTERID, StrKit.isBlank(value[6]) ? '0' : value[6])
                            .put(Organization.SALESCENTERNAME, value[7])
                            .put(Organization.ENABLED, value[10].equals("0") ? "1" : "0");
                    map_level2.put(value[0], temp);
                }

                // 导入四级机构：店铺
                if(!value[0].equals(value[2]) && !value[0].equals(value[4])){
                    ori_count_3++;
                temp = new JSONObject();
                temp.put(Organization.DISPLAYNAME, value[1]).put(Organization.PARENTID, value[4])
                            .put(Organization.WEBSITEID, value[8])
                            .put(Organization.SALESCENTERID, String.valueOf(StrKit.isBlank(value[6]) ? '0' : value[6]))
                        .put(Organization.SALESCENTERNAME, value[7])
                        .put(Organization.ENABLED, value[10].equals("0") ? "1" : "0")
                        .put(Organization.CITYCODE, value[2]);

                map_level3.put(value[0], temp);
                }

                if(!sql_class.contains("(0,'" + value[8] + "','" + value[9] + "'),") && value.length <= 11){
                    sql_class += "(0,'" + value[8] + "','" + value[9] + "'),";
                }

                if(i >= 10000){

                    map_count_1 += map_level1.size();
                    map_count_2 += map_level2.size();
                    map_count_3 += map_level3.size();
                    result = Organization.dao.load(map_level1, map_level2, map_level3,
                                                   sql_class.substring(0, sql_class.length() - 1) + sql_class_dup);
                    count_class += Integer.parseInt(result[1]);
                    count_1 += Integer.parseInt(result[2]);
                    count_2 += Integer.parseInt(result[3]);
                    count_3 += Integer.parseInt(result[4]);
                    map_level1.clear();
                    map_level1 = null;
                    map_level2.clear();
                    map_level2 = null;
                    map_level3.clear();
                    map_level3 = null;
                    map_level1 = new HashMap<String, JSONObject>(); // 一级机构：成都
                    map_level2 = new HashMap<String, JSONObject>(); // 二级机构：成都新都区
                    map_level3 = new HashMap<String, JSONObject>(); // 三级机构：新都店铺
                    i = 0;
                } else{
                    i++;
                }
            }
            result = Organization.dao.load(map_level1, map_level2, map_level3,
                                           sql_class.substring(0, sql_class.length() - 1) + sql_class_dup);
            count_class += Integer.parseInt(result[1]);
            count_1 += Integer.parseInt(result[2]);
            count_2 += Integer.parseInt(result[3]);
            count_3 += Integer.parseInt(result[4]);
        } catch(Exception e){
            e.printStackTrace();
            
        }
        finally{
            closeReader(reader);
        }

        mag = "导入完成!\r\n原始文件共:\r\n" + ori_count_1 + "条一级机构记录\r\n" + ori_count_2 + "条二级机构记录\r\n" + ori_count_3
                + "条三级机构记录\r\n" + "本次导入实际修改:\r\n" + count_1 + "条一级机构记录\r\n" + count_2 + "条二级机构记录\r\n" + count_3
                + "条三级机构记录\r\n" + count_class + "条网点类型记录";
        logger.info(mag);
        return mag;

    }

    private void closeReader(BufferedReader reader){
        if(reader != null){
            try{
                reader.close();
            } catch(IOException e1){}
            }
    }

    private boolean isValid(String[] value){
        try{
            if(value.length != 11){
                return false;
            }

            // for(int i = 0; i < value.length; i++){
            // if(!StrKit.notBlank(value[i])){
            // return false;
            // }
            // }

            return true;
        } catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
